<?php

namespace App\Http\Controllers\IndexManage;

use App\Biji;
use App\Book;
use App\Http\Controllers\Controller;

class BookController extends Controller
{
	/**
	 * @return array
	 */
    public function book(){
    	$user_id = session('user_id');
    	if($user_id){
    		$search_book = empty($_GET['search_book']) ? '' : $_GET['search_book'];
			$books = Book::get_books_by_user_id($user_id, $search_book);
			foreach ($books as $book){
				$book['bijis_count'] = count(Biji::get_bijis_by_book_id($book['book_id']));
			}
			return $this->successResponse('success', $books);
		}else{
			return $this->failResponse(trans('session_fail'));
		}
	}

	/**
	 * @return array
	 */
	public function add_book(){
		$user_id = session('user_id');
		if($user_id) {
			$insert['user_id'] = $user_id;
			$insert['book_title'] = empty($_POST['book_title']) ? '' : $_POST['book_title'];
			$exist_book = Book::get_book_by_user_id_and_book_title($insert['user_id'], $insert['book_title']);
			if(!$exist_book){
				if (Book::add($insert)) {
					return $this->successResponse();
				} else {
					return $this->failResponse('add_book_fail');
				}
			}else{
				return $this->failResponse('exist_book_fail');
			}
		}
	}
}
